﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    /// <summary>
    /// This class contains event handlers for context menu used by SheetView + Sheet databound to it
    /// </summary>
    /// <remarks>
    /// </remarks>
    public class PopupMenuEventHandlers
    {
        private Sheet sheet;
        private Cell cell;
        private SheetView sheetView;
        private int getColumn
        {
            get
            { 
                return cell.GetColumn;
            }
        }
        private int row;
        
        public delegate List<ToolStripMenuItem> PopulatorDelegate(Cell pCell);
        private Weekday Day
        {
            get
            {
                return (Weekday)getColumn - 1;
            }
        }
        private RowTag Tag
        {
            get
            {
                return sheetView.Rows[row].Tag as RowTag;
            }
        }
        
        
        public PopupMenuEventHandlers(Sheet pRefill, SheetView pDataGrid, Cell pCell, int pRow)
        {
            sheet = pRefill;
            sheetView = pDataGrid;
            cell = pCell;
            row = pRow;
        }        
        
        /// <summary>
        /// 
        /// </summary>
        /// <param Name="pCell">Ignored (pass null)</param>
        /// <returns></returns>
        internal List<ToolStripMenuItem> popUp_populatePopularShifts(Cell pCell)
        {
            var result = new List<ToolStripMenuItem>();
            var _howManyWeWant = Settings.Default.CONTEXT_MENU_number_of_popular_shifts_displayed;
            var _howManyWeHave = 0; // keeps track of how many we have added            
            
            /* By default, "Open - Close" is fixed On the top of the list
             * regardless of whether it actually appears in the schedule (and how many times if so).
             * It can be switched off by changing application pParameters. */
            bool _open_close_on_top = Settings.Default.CONTEXT_MENU_always_open_close_on_top;            
            
            if(_open_close_on_top)
            {
                ToolStripMenuItem open_close = new ToolStripMenuItem("open - close", null, new EventHandler(popUp_AddShift));
                ShiftStub ss = new ShiftStub();
                ss.Opening = true; ss.Closing = true;
                open_close.Tag = ss;
                result.Add(open_close);
                _howManyWeHave++;
            }
            
            foreach (KeyValuePair<int, List<ShiftStub>> kv in sheet.Tracker.GetMostPopular.Reverse())                        
                foreach (ShiftStub sf in kv.Value)
                {
                    var _is_this_one_open_till_close = (sf.Opening && sf.Closing);
                    if (_open_close_on_top && _is_this_one_open_till_close)
                    {
                        continue;
                    }
                    ToolStripMenuItem tsmi = new ToolStripMenuItem(sf.ToString(), null, new EventHandler(popUp_AddShift));
                    tsmi.Tag = sf;
                    result.Add(tsmi);
                    _howManyWeHave++;
                    if (_howManyWeHave >= _howManyWeWant)
                    {
                        return result;
                    }
                }
        
            return result;
        }

        internal void popUp_ClearSheet(object sender, EventArgs e)
        {
            if (MessageBox.Show(
                "Are you sure you want to clear this sheet completely?",
                "Clear entire sheet",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }
            sheet.ClearAllShifts();
            if (sheet is Rota)
            {
                (sheet as Rota).AllRefresh();
            }
            if (sheet is Template)
            {
                (sheet as Template).AllRefresh();
            }
            sheet.Modified = true;
            Sounds.Play(Sounds.Validated);
        }

        private void popUp_AddShift(object sender, EventArgs e)
        {
            if (!(sender is ToolStripMenuItem))
            {
                Program.LogError("popUp_AddShift here. sender is not ToolStripMenuItem, but " + sender.GetType().ToString() + " - why?", null);
                return;
            }

            ToolStripMenuItem me = (ToolStripMenuItem)sender;
            ShiftStub ss = me.Tag as ShiftStub;

            var _shiftsToAdd = new ShiftTandem();
            Shift toAdd = new Shift();
                        
            toAdd.Day = Day;
            toAdd.opening = ss.Opening;
            toAdd.closing = ss.Closing;

            toAdd.Start = ss.Start;
            toAdd.Finish = ss.End;

            _shiftsToAdd.Add(toAdd);

            if (sheet.Mode == SheetType.Rota)
            {
                (sheet as Rota).RemoveShifts(Day, Tag, false);
                (sheet as Rota).AddShifts(_shiftsToAdd, toAdd.Day, Tag, true);
            }
            else
            {
                (sheet as Template).RemoveShifts(Day, Tag, false);
                (sheet as Template).AddShifts(_shiftsToAdd, toAdd.Day, Tag, true);
            }
            
        }

        internal void popUp_DeleteShift(object sender, EventArgs e)
        {
            if (sheet.Mode == SheetType.Rota)
            {
                (sheet as Rota).RemoveShifts(Day, Tag, true);
            }
            if (sheet.Mode == SheetType.Template)
            {
                (sheet as Template).RemoveShifts(Day, Tag, true);
            }
        }

        internal void popUp_RemoveRow(object sender, EventArgs e)
        {
            if (MessageBox.Show(
                Resources.MESSAGEBOX_QUESTION_DeleteTemplateRow_MESSAGE,
                Resources.MESSAGEBOX_QUESTION_DeleteTemplateRow_CAPTION,                
                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                sheetView.RemoveRow(Tag);
                Sounds.Play(Sounds.Validated);
            }
        }

        internal void popUp_AddNotes(object sender, EventArgs e)
        {
            sheetView.AddNotes(getColumn, row);            
        }

        internal void popUp_RemoveNotes(object sender, EventArgs e)
        {
            var _cell = sheet[Tag][getColumn];
            _cell.Notes = string.Empty;
            _cell.Update();            

            Sounds.Play(Sounds.Validated);
        }

        private void popUp_ReassignShift(object sender, EventArgs e)
        {
            if (!(sender is ToolStripMenuItem))
            {
                Program.LogError("popUp_ReassignShift here. sender is not ToolStripMenuItem, but " + sender.ToString() + " - why?", null);
                return;
            }
            var _cell = sheet[Tag][getColumn];
            if (!_cell.IsEditable)
            {
                return;
            }
            var _me = (ToolStripMenuItem)sender;
            var _dest = (Int64)(_me.Tag); // id of the row who's getting that Shift

            var dr = SheetView.DragAction.move;
            if (_cell.MyCellType == CellType.Shift)
            {
                dr = SheetView.DragAction.overwrite;
            }                
            sheetView.DoTheDrop(getColumn, row, getColumn, sheetView.GetRowByEmployeeID(_dest).Index, dr);
        }

        internal void popUp_ManageHolidays(object sender, EventArgs e)
        {            
            if (cell.MyCellType != CellType.Holiday)
            {
                Debugger.Break();
                return;
            }
            Program.frmMain.EditHolidays(
                cell.GetStatusID[0],
                (bool?)null);            
        }

        internal void popUp_ManageRequest(object sender, EventArgs e)
        {
            var _myRequests = cell.GetMyRequests;
            if (_myRequests.Length == 0)
            {
                Debugger.Break();
                return;
            }
            if (_myRequests.Length > 1)
            {
                MessageBox.Show(
                    Resources.MESSAGEBOX_INFORMATION_MultipleRequestsEditAttempt_MESSAGE,
                    Resources.MESSAGEBOX_INFORMATION_MultipleRequestsEditAttempt_CAPTION,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }
            Program.frmMain.EditRequest(_myRequests[0].ID);
            
        }

        internal void popUp_SeeHolidays(object sender, EventArgs e)
        {
            var _id = Tag.Int64Value;
            Program.frmMain.HolidaysTab_SelectEmployee(_id);
            Sounds.Play(Sounds.Pageturn);
        }

        internal void popUp_ClearRow(object sender, EventArgs e)
        {
            if (MessageBox.Show(
                Resources.MESSAGEBOX_QUESTION_DeleteAllShiftsInARow_MESSAGE,
                Resources.MESSAGEBOX_QUESTION_DeleteAllShiftsInARow_CAPTION,
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }
            if (sheet.Mode == SheetType.Rota)
            {
                (sheet as Rota).RemoveShiftsEntireRow(Tag, true);
            }
            else
            {
                (sheet as Template).RemoveShiftsEntireRow(Tag, true);
            }
        }

        internal void popUp_Sick(object sender, EventArgs e)
        {
            if (sheet.Mode != SheetType.Rota)
            {
                Debugger.Break();
                return;
            }
            
            sheetView.SuspendLayout();
            (sheet as Rota).RemoveShifts(Day, Tag, true);
            
            var _row = SQLiteAccess.SpawnHolidaysRow();
            var _holiday = new Holiday(_row)
            {
                empID = Tag.Int64Value,
                type = HolidayType.sick,
                startDate = cell.GetMyDate,
                endDate = cell.GetMyDate,
                pending = false
            };
            SQLiteAccess.AddNewHoliday(_holiday.empID, _holiday.row);
            sheetView.ResumeLayout();
            sheetView.CurrentCell = sheetView[getColumn, row];                        
        }

        internal void popUp_UnSick(object sender, EventArgs e)
        {
            if (sheet.Mode != SheetType.Rota)
            {
                Debugger.Break();
                return;
            }
            sheetView.SuspendLayout();
            SQLiteAccess.DeleteHoliday(cell.GetStatusID[0]);
            sheetView.ResumeLayout();
            sheetView.CurrentCell = sheetView[getColumn, row];
            Sounds.Play(Sounds.Validated);
        }

        internal void popUp_GetPhoneNumbers(object sender, EventArgs e)
        {
            var employeeID = Tag.Int64Value;
            var phones = SQLiteAccess.GetEmployeePhoneNumbers(employeeID);            
            var window = new PhoneNumbers(
                SQLiteAccess.GetEmployeeFullName(employeeID),
                phones[0],
                phones[1]);
            window.ShowDialog();
        }

        internal List<ToolStripMenuItem> popUp_GetOtherEmployees(Cell pCell)
        {
            var _result = new List<ToolStripMenuItem>();
            var _currentID = sheetView.GetEmployee(row).Employee.ID;
            foreach (var _alternative_employee in sheetView.GetEmployees())
            {
                if (_alternative_employee.Employee.ID == _currentID)
                {
                    continue;
                }

                ToolStripMenuItem _item;
                foreach (Shift s in pCell.Shifts)
                {
                    if (_alternative_employee.CanWork(s))
                    {
                        _item = new ToolStripMenuItem(_alternative_employee.Employee.firstName, null, new EventHandler(popUp_ReassignShift));
                        _item.Tag = _alternative_employee.Employee.ID;
                        _result.Add(_item);
                        break;
                    }
                }
            }

            return _result;
        }




    }
}
